package com.muyu.common.security.utils;

import lombok.extern.log4j.Log4j2;

import java.awt.*;
import java.awt.image.BufferedImage;


/**
 * 渲染图片颜色 ApplyColorToImage
 *
 * @author LeYang
 * on 2025/3/13
 */

@Log4j2
public class ApplyColorToImage {
    public static BufferedImage applyColorToImage(BufferedImage image, String color) {
        try {
            // 转换颜色字符串为 RGB 值
            Color targetColor = Color.decode(color);

            // 获取图像宽度和高度
            int width = image.getWidth();
            int height = image.getHeight();

            // 创建新图像
            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = newImage.createGraphics();

            // 设置抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 绘制原始图像
            g2d.drawImage(image, 0, 0, null);

            // 创建颜色过滤器
            g2d.setComposite(AlphaComposite.SrcAtop);
            g2d.setColor(targetColor);
            g2d.fillRect(0, 0, width, height);

            g2d.dispose();
            return newImage;
        } catch (Exception e) {
            log.error("Color application failed: ", e);
            return null;
        }
    }
}
